package com.infore.gateway.main.filter;

import com.infore.gateway.main.constant.GatewayConstant;
import com.infore.gateway.main.enums.ResultStatus;
import com.infore.gateway.main.feign.IAuthService;
import com.infore.gateway.main.model.ResultEntity;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;

/**
 *
 */
@Slf4j
@Component
public class AuthorizeGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private IAuthService authService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 1. 登录 直接放行
        if (request.getURI().getPath().contains(GatewayConstant.LOGIN_URI)) {
            return chain.filter(exchange);
        }
        // 2. 如果是注册 直接放行
        if (request.getURI().getPath().contains(GatewayConstant.REGISTER_URI)) {
            return chain.filter(exchange);
        }
        // 3. 验证token是否有效，调用蔡接口
        ResultEntity resultEntity = authService.checkAndRenewToken();
        if (resultEntity.getCode() != ResultStatus.SUCCESS.getStatusCode()) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            byte[] bytes = "{\"code\":401,\"msg\":\"authorize not passed!\"}".getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        }
        // 解析通过, 则放行
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        // 设置过滤器的执行顺序,可以根据需要进行调整 数字越小越先执行
        return 1;
    }

}
